package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 类型列表查询
     * @return
     */
    public Result quertTypeList(){
        //先查rdeis
        String key= RedisConstants.CACHE_SHOP_TYPE;
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        //有就转换类型返回
        if(StrUtil.isNotBlank(shopTypeJson)){
            List<ShopType> typeList = JSONUtil.toList(shopTypeJson,ShopType.class);
            return Result.ok(typeList);
        }

        //没有查数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //数据库没有报错
        if(typeList== null || typeList.isEmpty()){
            return Result.fail("查询分类为空");
        }
        //数据库查询到转换类型
        String typeJson = JSONUtil.toJsonStr(typeList);

        //存入
        stringRedisTemplate.opsForValue().set(key,typeJson);

        //返回
        return Result.ok(typeList);
    }
}
